﻿using Microsoft.Practices.Unity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using WebDocDB.DocumentDBManager;
using WebDocDB.Managers;
using WebDocDB.Models;

namespace WebDocDB.Controllers
{
    public class DocumentsController : Controller
    {
        private IAccountManager accountManager;
        private IDocumentsManager documentsManager;

        public DocumentsController(IAccountManager accountManager, IDocumentsManager documentsManager)
        {
            this.accountManager = accountManager;
            this.documentsManager = documentsManager;
        }

        // GET: Documents/Create
        public ActionResult Create(string collectionLink, string collectionID)
        {
            var docModel = new Models.Document();
            docModel.CollectionLink = collectionLink;
            docModel.CollectionID = collectionID;
            docModel.ID = "fakeId"; //Required by Model
            return PartialView("_Create", docModel);
        }

        // POST: Documents/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        public async Task<JsonResult> Create(Models.Document docModel)
        {
            if (ModelState.IsValid)
            {
                if (accountManager.GetAccountSettings() != null)
                {
                    try
                    {                        
                        await documentsManager.AddDocument(docModel.CollectionLink, docModel.JsonText);
                        return Json(new AjaxResponse() { Success = true, Values = new { CollectionLink = docModel.CollectionLink } });
                    }
                    catch (Exception ex)
                    {
                        return Json(new AjaxResponse() { Success = false, Message = ex.Message });
                    }
                }
            }

            return Json(new AjaxResponse() { Success = false, Message = "Invalid data" });
        }

        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        public async Task<ActionResult> DocumentsList(string collectionLink)
        {
            if (accountManager.GetAccountSettings() != null)
            {
                var collections = await documentsManager.GetAllDocuments(collectionLink);
                return PartialView("_DocumentsList", collections.OrderBy(db => db.ID).ToList());
            }

            return RedirectToAction("Index", "Home");
        }

        // POST: Documents/Delete/5
        [HttpPost]
        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        public async Task<JsonResult> Delete(string documentLink)
        {
            if (accountManager.GetAccountSettings() != null)
            {
                try
                {
                    await documentsManager.DeleteDocument(documentLink);
                    return Json(new AjaxResponse() { Success = true });
                }
                catch (Exception ex)
                {
                    return Json(new AjaxResponse() { Success = false, Message = ex.Message });
                }

            }

            return Json(new AjaxResponse() { Success = false, Message = "Invalid data" });
        }

        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        public PartialViewResult ShowQueryManager(string collectionLink)
        {
            return PartialView("_QueryManager", new QueryViewModel() { CollectionLink = collectionLink });
        }

        [HttpPost]
        public async Task<JsonResult> ExecuteQuery(string queryText, string collectionLink)
        {
            if (accountManager.GetAccountSettings() != null)
            {
                if (!string.IsNullOrWhiteSpace(queryText))
                {
                    string message = "";
                    try
                    {
                        var JsonStringResult = await documentsManager.ExecuteQuery(collectionLink, queryText);                        
                        return Json(new AjaxResponse() { Success = true, Values = JsonStringResult });
                    }                   
                    catch (AggregateException aex)
                    {
                        foreach (var exception in aex.InnerExceptions)
                            message += exception.Message + Environment.NewLine;
                    }
                    catch (Exception ex)
                    {
                        message = ex.Message;
                    }

                    return Json(new AjaxResponse() { Success = false, Message = message }); ;                    
                }                
            }

            return Json(new AjaxResponse() { Success = false, Message = "Invalid data" });
        }        
    }
}